const app = getApp()

Page({
  data: {
    oldPassword: '',
    newPassword: ''
  },

  onShow() {
    wx.setNavigationBarTitle({
      title: '修改密码'
    })
  },

  handleInput(e) {
    const type = e.currentTarget.dataset.type
    this.setData({
      [type]: e.detail.value
    })
  },

  handleSubmit() {
    const { oldPassword, newPassword } = this.data
    const userInfo = wx.getStorageSync('userInfo')
    
    if (!oldPassword || !newPassword) {
      wx.showToast({
        title: '请填写完整信息',
        icon: 'none'
      })
      return
    }

    wx.showLoading({
      title: '修改中'
    })

    wx.cloud.callFunction({
      name: 'updatePassword',
      data: {
        name: userInfo.username,
        oldPassword,
        newPassword
      },
      success: res => {
        wx.hideLoading()
        if (res.result && res.result.success) {
          wx.showToast({
            title: '修改成功，请重新登录',
            icon: 'success',
            duration: 2000,
            success: () => {
              wx.removeStorageSync('userInfo')
              getApp().globalData.userInfo = null
              
              setTimeout(() => {
                wx.reLaunch({
                  url: '/pages/login/login'
                })
              }, 2000)
            }
          })
        } else {
          wx.showToast({
            title: res.result.msg || '修改失败',
            icon: 'none'
          })
        }
      },
      fail: err => {
        wx.hideLoading()
        wx.showToast({
          title: '修改失败，请重试',
          icon: 'none'
        })
      }
    })
  }
}) 